package com.zhouixi.listener;
import com.alibaba.fastjson.JSONObject;
import com.zhouixi.entity.Message;
import com.zhouixi.repository.SessionManager;
import jakarta.annotation.PostConstruct;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

@Component
@RocketMQMessageListener(
        consumerGroup = "im_consumer_group_${nodeId}",
        topic = "${rocketmq.producer.topic}",
        selectorExpression = "${nodeId}"
)
@Slf4j
public class RocketListener implements RocketMQListener<String> {

    private final SessionManager sessionManager;

    public RocketListener(SessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }


    @Override
    public void onMessage(String message) {
        // 从消息中解析接收者ID（需自定义消息格式）
        Long receiverId = parseReceiverId(message);
        WebSocketSession session = sessionManager.getSession(receiverId);
        log.info("接到消息了: {}", message);
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage(message));
            } catch (Exception e) {
                // 记录错误日志
                log.error("发生了错误",e);
            }
        }
    }

    public Long parseReceiverId(String content) {
        Message message  = JSONObject.parseObject(content, Message.class);
        return message.getReceiverId();
    }
}
